<template>
  <div> 
    <div class="com_main">
      <!-- <form-list></form-list> -->
      <div class="com-title display-flex mb20">
        <div class="com-title_lable"></div>
        <div class="title-text flex-1">表单管理</div>
        <el-button @click="showForm(1)"> 新增</el-button>
        <el-button @click="clearSearchAll()"> 刷新</el-button>
        <el-button class="btn-blue" @click="getDataList()"> 查询</el-button>
        <el-button @click="searchForm = {}"> 清空</el-button>
        <el-button @click="isSearch = false" v-if="isSearch">收起</el-button>
        <el-button @click="isSearch = true" v-if="!isSearch">展开</el-button>
      </div>

      <el-form v-if="isSearch" :model="searchForm" label-width="124px" class="mb20">
        <el-row type="flex" :gutter="40" class="flex-wrap">
          <el-col :span="8">
            <el-form-item label="名称">
              <el-input v-model="searchForm.fullName" placeholder="请输入名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分组名称">
              <el-select v-model="resModel" placeholder="请选择" @change="resChange">
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.showName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="pageBean.data" stripe border header-row-class-name="tab-header">
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="fullName" label="名称"></el-table-column>
        <el-table-column prop="createDate" label="创建时间"></el-table-column>
        <el-table-column prop="modifyDate" label="修改时间"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.status === '1'">启用</el-tag>
            <el-tag type="danger" v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="resShowName" label="分组名称"></el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="primary" plain @click="edit(scope.row.id)">编辑</el-button>
            <el-button type="warning" plain @click="saveObjectStatus(scope.row.id, '0')"
              v-if="scope.row.status === '1'">禁用
            </el-button>
            <el-button type="success" plain @click="saveObjectStatus(scope.row.id, '1')" v-else>启用
            </el-button>
            <el-button type="danger" plain @click="del(scope.row.id)" class="ml-10">删除</el-button>
            <el-popover placement="bottom" trigger="click" class="ml-10">

              <el-button type="primary" plain @click="formDesigner(scope.row.id)">表单设计</el-button>
<!--              <el-button type="primary" plain @click="yddTest(scope.row.id, 'pc')">测试</el-button>-->
              <el-button type="primary" plain @click="yddTest(scope.row.id, 'app')">移动端测试</el-button>
              <el-button type="primary" plain @click="listDesigner(scope.row.id)" v-if="scope.row.state == 2">列表设计</el-button>
<!--              <el-button type="primary" plain @click="listPreview(scope.row.id)">列表预览</el-button>-->
              <el-button type="primary" plain @click="downLoad(scope.row.id,scope.row.fullName)">下载代码</el-button>
              <el-button type="primary" plain @click="preview(scope.row.id)">预览代码</el-button>
              <el-button type="primary" plain @click="designPreview(scope.row.id)">设计预览</el-button>
              <el-button type="primary" plain @click="publishForm(scope.row.id)">发布</el-button>
              <el-button type="primary" plain @click="copyForm(scope.row.id)">复制</el-button>
              <el-button slot="reference" plain class="ml10">更多</el-button>
            </el-popover>

          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="text-center mt10" @size-change="sizeChangeHandle" @current-change="currentChangeHandle"
        :current-page="pageBean.currentPage" :page-sizes="[5, 10, 20, 50, 100]" :page-size="pageBean.pageSize"
        :total="pageBean.totalPage" layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
      <Preview v-if="previewVisible" ref="preview" @close="previewVisible=false" />

      <form-baseInfo v-show="formShow" :editData="editData" @hideForm="hideForm" @getDataList="getDataList"></form-baseInfo>
    </div>
  </div>
</template>

<script>
import devFormService from "@/service/dev/DevFormService";
import FormBaseInfo from "../formBaseInfo/index.vue";
import Preview from "./Preview"
import ServiceConfig from "@/service/ServiceConfig";
// import { getCopyForm, setCopyForm } from "@/service/TokenUtils";

const serviceConfig = ServiceConfig.getInstance();
export default {
  name: "FormList",
  components: { FormBaseInfo ,Preview},
  data() {
    return {
      isSearch: false,
      searchForm: {},
      resId: "", //资源id
      pageBean: {
        currentPage: 1,
        pageSize: 10,
        data: [],
        totalPage: 0,
      },
      formShow: false,
      editData:{},
      previewVisible:false,
      options:[],
      resModel:''
    }
  },
  async created() {
    var str=location.href;
    this.resId = str.split('formList/')[1];
    await this.getDataList();
    let params = {
      currentPage: 1,
      pageSize: 10,
      parentId: '6498e9e1-2fe3-41ec-89a1-6860a230a610'
    };
    devFormService.queryResPage(params).then((res)=>{
      this.options = res.data.data
    })
  },
  methods: { 
    resChange(e){
      this.resId = e;
    },
     /**
     * 表单设计
     */
    formDesigner(id) {
      const routeData = this.$router.resolve({
        path: '/formDesigner/designer',
        query:{
          id: id,
          abc:"23423"
        }
      });
      window.open(routeData.href, '_blank');
    },
      /**
     * 移动端测试
     */
     yddTest(id, type) {
      let url = ""
      if (type == "pc") {
        url = "/test/perview"
      }else{
        url = "/test/mobilePerview"
      }
      const routeData = this.$router.resolve({
        path: url,
        query:{
          id: id
        }
      });
      window.open(routeData.href, '_blank');
    },
    /**
     * 设计预览
     */
    designPreview(id) {
      const routeData = this.$router.resolve({
        path: '/designPreview/preview',
        query:{
          id: id,
          isPreview:true,
        }
      });
      window.open(routeData.href, '_blank');
    },
      /**
     * 列表设计
     */
     listDesigner(id) {
      const routeData = this.$router.resolve({
        path: '/listDesigner/designer',
        query:{
          id: id
        }
      });
      window.open(routeData.href, '_blank');
    },
      /**
     * 列表预览
     */
     listPreview(id) {
      const routeData = this.$router.resolve({
        path: '/listPreview/preview',
        query:{
          id: id
        }
      });
      window.open(routeData.href, '_blank');
    },
    showForm(e) {
      if(e == 1){
        this.editData = {}
      }
      this.formShow = true
    },
    hideForm() {
      this.formShow = false
    },
    /**
     * 列表查询
     */
    async getDataList(currentPage) {
      // 新增、搜索，返回到第一页
      if (currentPage) {
        this.pageBean.currentPage = currentPage;
      }
      try {
        let params = {
          currentPage: this.pageBean.currentPage,
          pageSize: this.pageBean.pageSize,
          resId: this.resId,
          ...this.searchForm,
        };
        const resp = await devFormService.queryPage(params);
        if (resp.status !== 200) {
          throw new Error("接口请求失败, status: " + resp.status);
        }
        this.pageBean.totalPage = resp.data.total;
        this.pageBean.data = resp.data.records;
      } catch (e) {
        this.$message({
          showClose: true,
          message: "加载列表失败，错误：" + e.message,
          type: "error",
        });
      }
    },

    /**
     * 当前页
     */
    currentChangeHandle(val) {
      this.pageBean.currentPage = val;
      this.searchForm = {};
      this.getDataList();
    },

    /**
     * 每页数
     */
    sizeChangeHandle(val) {
      this.pageBean.pageSize = val;
      this.pageBean.currentPage = 1;
      this.getDataList();
    },

    /**
     * 查询条件重置刷新
     */
    clearSearchAll() {
      this.pageBean = {
        currentPage: 1,
        pageSize: 10,
        data: [],
        totalPage: 0,
      };
      this.searchForm = {};
      this.getDataList();
    },

    /**
     * 新增
     */
    add() {
      this.$refs.formInput.init(this.resId);
    },

    /**
     * 修改
     */
    edit(id) {
      let params = {
        id:id
      }
      devFormService.queryById(params).then((res)=>{
        console.log(res.data);
        console.log(JSON.parse(res.data.formData));
        this.editData = res.data;
        this.showForm()
      });
    },
    publishForm(id) {
      this.$router.push({ path: "/formDesigner/formPublish/" + id });
    },

    copyForm(id) {
      try {
        devFormService.copyById({ id: id }).then(() => {
            this.getDataList();
          })
      } catch (e) {
        this.$message({
          showClose: true,
          message: "复制失败，错误：" + e.message,
          type: "error",
        });
      }
    },

    pasteForm(id) {
      // try {
      //   let copyForm = getCopyForm();
      //   this.$confirm("确认是否粘贴" + copyForm.name + "的内容?", "提示", {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     type: "warning",
      //   })
      //     .then(() => {
      //       let param = {
      //         id: id,
      //         copyId: copyForm.id,
      //       };
      //       devFormService.pasteById(param).then(data => {
      //         if (data.status === 200) {
      //           this.$message({
      //             type: "success",
      //             message: "粘贴成功!",
      //           });
      //         } else {
      //           this.$message({
      //             type: "error",
      //             message: data.data.msg,
      //           });
      //         }
      //
      //       });
      //     })
      //     .catch(() => { });
      // } catch (e) {
      //   this.$message({
      //     showClose: true,
      //     message: "粘贴失败，错误：" + e.message,
      //     type: "error",
      //   });
      // }

    },



    /**
     * 启用/禁用
     */
    saveObjectStatus(id, status) {
      let str;
      if (status === "0") {
        str = "禁用";
      } else if (status === "1") {
        str = "启用";
      }
      let params = {
        id: id,
        status: status,
      };
      this.$confirm("确认是否" + str + "?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          devFormService.saveBatch([params]).then(() => {
            this.$message({
              type: "success",
              message: str + "成功!",
            });
            this.getDataList();
          });
        })
        .catch(() => { });
    },

    /**
     * 删除
     */
    del(id) {
      console.log(id);
      this.$confirm("确认是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          devFormService.delectById({ id: id }).then(() => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getDataList();
          });
        })
        .catch(() => { });
    },
    downLoad(id,name){
      devFormService.downLoad({ id: id }).then((res)=>{
        console.log(res)
        let blob = new Blob([res.data],{type:'application/zip'});
        let fileName = name + '.zip';
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
      })
    },
    preview(id){
      console.log(id);
      this.previewVisible = true
      this.$nextTick(() => {
        this.$refs.preview.init(id)
      })
    }
  }
}
</script>
<style scoped>
  .ml-10{
    margin-left: 10px;
  }
</style>
 